package com.app.cpcap.vraptor;

import java.io.ByteArrayInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;


import org.springframework.util.ResourceUtils;

import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;


import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;

import com.app.cpcap.bean.Registro;
import com.app.cpcap.dao.DaoFactory;
import com.app.cpcap.lib.Restrito;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;

@Resource
public class RelatorioController {
	private DaoFactory dao;
	private Validator validator;
	private Result result;
	private ServletContext context;

	public RelatorioController(DaoFactory dao, Validator validator,
			Result result, ServletContext context) {
		super();
		this.dao = dao;
		this.validator = validator;
		this.result = result;
		this.context = context;
	}

	@Restrito
	@Path("/registro/relatorio")  
	public InputStream relatorio(List<Registro> registros){
		Map<String, Long> parameters = new HashMap<String, Long>();  
		List<Registro> regList = new ArrayList<Registro>();
		for(Registro registro:registros){
			regList.add(dao.getRegistro().get(registro.getId()));
		}
		parameters.put("IDP", 3L);  
		JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(regList);    
		try {    
			String path = context.getRealPath("/WEB-INF/jasper/relatorio_registro.jasper");
			File jasperFile = ResourceUtils.getFile(path);    
			InputStream jasperStream = new FileInputStream(jasperFile);    
			byte[] bytes = JasperRunManager.runReportToPdf(jasperStream, parameters, ds);    
			return new ByteArrayInputStream(bytes);    
		} catch (Exception e) {    
			e.printStackTrace();  
		}    
		return null;    
	}
	
	@Restrito
	@Path("/registro/relatorio/{registro.id}")  
	public InputStream relatorioRegistro(Registro registro){    
		Map<String, Long> parameters = new HashMap<String, Long>();
		List<Registro> registros = new ArrayList<Registro>();
		registros.add(dao.getRegistro().get(registro.getId()));
		parameters.put("IDP", 3L);  
		JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(registros);    
		try {    
			String path = context.getRealPath("/WEB-INF/jasper/relatorio_registro.jasper");
			File jasperFile = ResourceUtils.getFile(path);    
			InputStream jasperStream = new FileInputStream(jasperFile);    
			byte[] bytes = JasperRunManager.runReportToPdf(jasperStream, parameters, ds);    
			return new ByteArrayInputStream(bytes);    
		} catch (Exception e) {    
			e.printStackTrace();  
		}    
		return null;    
	}
}
